package org.wzl.todolisthelper.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.wzl.todolisthelper.domain.User;
import org.wzl.todolisthelper.dto.JsCode2SessionResult;
import org.wzl.todolisthelper.exception.BizException;
import org.wzl.todolisthelper.service.ProfileService;
import org.wzl.todolisthelper.service.WXService;
import org.wzl.todolisthelper.utils.RestTemplateUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class WXServiceImpl implements WXService {

    @Value("${wx.appid}")
    private String appId;

    @Value("${wx.appSecret}")
    private String secret;

    @Resource
    private ProfileService profileService;

    @Override
    public JsCode2SessionResult jscode2session(String code) {
        //调用微信接口获取wx_id
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", secret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        JsCode2SessionResult jsCode2SessionResult = RestTemplateUtil.get(url, map, JsCode2SessionResult.class);
        if (!Objects.isNull(jsCode2SessionResult.getErrCode())) {
            throw new BizException("wxCode获取失败");
        }
        log.info("微信用户登录成功,{}", jsCode2SessionResult);

        //通过wx_id创建或获取用户信息
        User user = profileService.addUserIfNotExists(jsCode2SessionResult);
        StpUtil.login(user.getId());
        jsCode2SessionResult.setToken(StpUtil.getTokenInfo().tokenValue);
        //返回token
        return jsCode2SessionResult;
    }
}
